<template>
  <a-modal
    width="60%"
    :visible="visible"
    title-align="center"
    @cancel="handleCancel"
    @ok="handleBeforeOk"
    unmount-on-close
    :mask-closable="false"
  >
    <template #title>
      <div>{{ allForm?.id ? '编辑' : '新增' }}工号方案</div>
    </template>
    <a-form
      ref="refForm"
      :rules="rules1"
      :model="allForm"
      style="width: 66%; margin: auto"
      auto-label-width
      :disabled="disabledAll"
    >
      <a-form-item field="name" label="方案名称：" required>
        <a-input
          placeholder="请输入"
          style="width: 350px"
          v-model="allForm.name"
        />
      </a-form-item>
    </a-form>
    <a-divider />
    <a-space style="padding: 0 20px 20px 20px; display: flex">
      <!-- <a-button @click="addField" v-if="!disabledAll">增加前缀</a-button> -->
      <a-dropdown>
        <a-button v-show="!disabledAll">增加字段</a-button>
        <template #content>
          <a-doption @click="addField">自定义字段</a-doption>
          <a-dsubmenu :value="1">
            <template #default>智能填充</template>
            <template #content>
              <a-doption :disabled="disabled" @click="timer(1)">年月</a-doption>
              <a-doption :disabled="disabled" @click="timer(2)"
                >年月日</a-doption
              >
            </template>
          </a-dsubmenu>
        </template>
      </a-dropdown>
    </a-space>
    <a-space style="width: 100%; align-items: center" direction="vertical">
      <a-space v-for="(item, ind) in allForm.details" :key="item.prefixName">
        <a-form
          :model="allForm.details"
          :rules="rules1"
          :disabled="disabledAll"
        >
          <a-form-item hide-label>
            <a-space>
              <a-input
                style="width: 200px; margin-right: 20px"
                v-model="item.prefixName"
                :disabled="!item.editKey"
                :placeholder="item.placeholder"
              >
                <template #suffix>
                  <icon-delete
                    v-show="item.del && !disabledAll"
                    style="cursor: pointer"
                    @click="delField(ind)"
                  />
                </template>
              </a-input>
              <a-input
                v-model="item.prefixValue"
                :disabled="!item.editValue"
                style="width: 200px"
                placeholder="请输入"
              ></a-input>
            </a-space>
          </a-form-item>
        </a-form>
      </a-space>
      <a-space>
        <a-form>
          <a-form-item hide-label>
            <a-space>
              <a-input
                style="width: 200px; margin-right: 20px"
                placeholder="流水号"
                disabled
              >
              </a-input>
              <a-input
                v-model="allForm.num"
                disabled
                style="width: 200px"
                placeholder="请输入"
              ></a-input>
            </a-space>
          </a-form-item>
        </a-form>
      </a-space>
    </a-space>
    <a-space class="job-number">
      <p>工号预览：{{ jobNumber }}</p>
    </a-space>

    <a-space style="padding-left: 106px">
      <a-form
        style="width: 635px; margin: auto"
        :model="allForm"
        :rules="rules2"
        ref="refForm2"
        :disabled="disabledAll"
      >
        <a-form-item
          field=""
          tooltip="流水号当前值”是指系统当前分组产生的流水号值:当前值修改保存后，流水号将从当前值继续生成。"
          label="流水号当前值："
        >
          <a-input
            disabled
            v-model="allForm.nowValue"
            placeholder="系统默认生成"
          />
        </a-form-item>
        <a-form-item field="positionSequenceId" label="所属公司">
          <!-- <a-select
            :disabled="disabledAll"
            :options="props.list"
            placeholder="请选择"
            v-model="allForm.positionSequenceId"
          >
          </a-select> -->
          <a-tree-select
            :disabled="allForm.id ? true : false"
            :fieldNames="{
              key: 'id',
              title: 'name'
            }"
            :data="organizationList"
            v-model="allForm.positionSequenceId"
            placeholder="请选择"
            @change="handleSequence"
          ></a-tree-select>
        </a-form-item>

        <!-- <a-form-item field="post" label="适用工作性质">
          <a-select
            placeholder="请选择"
            :disabled="disabledAll"
            v-model="allForm.useScope"
          >
            <a-option>全职</a-option>
            <a-option>兼职</a-option>
          </a-select>
        </a-form-item> -->
        <!-- <a-form-item field="post" label="适用员工性质">
          <a-select
            placeholder="请选择"
            :disabled="disabledAll"
            v-model="allForm.useScope"
          >
            <a-option>全职</a-option>
            <a-option>兼职</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="post" label="适用员工状态">
          <a-select
            placeholder="请选择"
            :disabled="disabledAll"
            v-model="allForm.useScope"
          >
            <a-option>全职</a-option>
            <a-option>兼职</a-option>
          </a-select>
        </a-form-item> -->
        <!-- <a-form-item v-show="!disabledAll" label="启用状态">
          <a-switch
            v-model="allForm.status"
            checked-color="#409eff"
            :checked-value="1"
            :unchecked-value="2"
          />
        </a-form-item> -->
      </a-form>
    </a-space>
  </a-modal>
</template>
<script lang="tsx" setup>
import { controldataTreeFilter, flatTree } from '@/utils/utils';
import clonedeep from 'lodash.clonedeep';
import {
  PostScheme,
  EditScheme,
  RepeatScheme,
  GetScheme,
  CheckJobNumToOrganizaitonId
} from '@/apis/management/personnel/baseSetting/TransactionSetting';
import { schemeType } from '@/apis/management/personnel/baseSetting/TransactionSetting/type';
import { GetOrganizationList } from '@/apis/management/organization/organizationManagement/index';
import dayjs from 'dayjs';
import { Modal, Message } from '@arco-design/web-vue';

const props = withDefaults(
  // 参数说明
  defineProps<{
    visible?: boolean; // 请求table数据的函数
    oldData: schemeType;
    refreshFn?: any;
    show?: boolean;
    editName?: string;
  }>(),
  {}
);

watch(
  () => props.visible,
  (newVal: boolean) => {
    if (newVal) {
      if (props.oldData?.id) {
        allForm.value = clonedeep(props.oldData);
        allForm.value.details.forEach((el, index, arr) => {
          // 判断是否是年月的前缀，年月前缀一定是在数组的最后一个
          const isLastIndex = index === arr.length - 1;
          el.editKey = !isLastIndex;
          el.editValue = !isLastIndex;
          el.del = true;
        });
      }

      getSchemeData();
      getOrganizationList();
    } else {
      init();
    }
  }
);

let disabledAll = ref(false);
watch(
  () => props.show,
  (val) => {
    disabledAll.value = val;
  }
);

const handleSequence = async (id: number) => {
  try {
    console.log(id);
    const res = await CheckJobNumToOrganizaitonId({
      id
    });
    console.log(res);
  } catch (error: unknown) {
    console.log(error);
  }
};

// 初始值
const allForm = ref<schemeType>({
  nowNum: 1,
  isDown: 2,
  numId: 0,
  prefix: '',
  num: '000001', // 写死6位
  digit: 6,
  details: [
    {
      order: 1,
      prefixName: '前缀',
      prefixValue: '',
      del: true,
      placeholder: '自定义输入',
      editKey: true,
      editValue: true,
      auto: 1
    }
  ]
});

const rules1 = {
  name: [
    {
      required: true,
      message: '请输入'
    },
    {
      validator: async (value: string, cb: any) => {
        try {
          if (value === props.editName && allForm.value.id) {
            //
          } else {
            const res = await RepeatScheme({ name: value });
            if (res.code) cb(`${res.msg}`);
          }
        } catch (error: any) {
          Message.error(error);
          console.log(error);
        }
      }
    }
  ]
};

const rules2 = {
  positionSequenceId: [
    {
      required: true,
      message: '请选择'
    }
  ]
};

const disabled = ref(false); // 年月日 是否禁用
const emit = defineEmits(['update:visible', 'init']);

// 工号预览
const jobNumber = computed(() => {
  let str = '';
  if (allForm.value.details) {
    allForm.value.details.map((ele) => {
      str += ele.prefixValue;
    });
    return str + (allForm.value.num || '') + (allForm.value.suffix || '');
  }
  return '';
});

let schemeList = ref([]); // 储存已有的工号列表数据

const getSchemeData = async () => {
  try {
    const { content } = await GetScheme({
      pageNumber: 0,
      pageSize: -1
    });
    schemeList.value = content;
  } catch (error: unknown) {
    console.log(error);
  }
};

let organizationList = ref([]); // 储存组织数据
// 重新组合树数据(根据需要来重组树结构中的属性字段，用来新增判断是否为叶子节点信息)
const dealTreeData = (treeData: any) => {
  const data = treeData.map((item: any) => ({
    ...item,
    ...controldataTreeFilter(item.ctlValue),
    // 新增叶子节点字段
    // isLeaf: item.children ? false : true,
    disabled:
      item.node === '公司' &&
      !schemeList.value.find((el) => el.positionSequenceId === item.id) &&
      item.numId === 0
        ? false
        : true,
    // 新增是否能被选中字段，默认只有叶子节点可以选
    // selectable: item.children ? false : true,
    // 如果children为空数组，则置为null
    children:
      item.children && item.children.length ? dealTreeData(item.children) : null
  }));
  return data;
};

// 获取部门数据
const getOrganizationList = async () => {
  const res: any = await GetOrganizationList({});
  organizationList.value = dealTreeData(res);
};

// 初始化数据
const init = () => {
  allForm.value = {
    nowNum: 1,
    num: '000001', // 写死6位
    isDown: 2,
    prefix: '',
    digit: 6,
    details: [
      {
        order: 1,
        prefixName: '前缀',
        prefixValue: '',
        del: true,
        placeholder: '自定义输入',
        editKey: true,
        editValue: true,
        auto: 1
      }
    ]
  };
  // emit('init', initData);
};

const refForm = ref();
const refForm2 = ref();
// 删除前缀
const delField = (ind: number) => {
  if (allForm.value.details.length > 1) {
    allForm.value.details.splice(ind, 1);
    disabled.value = allForm.value.details.some(
      (ele) => ele.prefixName === '年月' || ele.prefixName === '年月日'
    );
    return;
  }
  Message.warning('必须有一个前缀');
};
// 新增前缀
const addField = () => {
  if (allForm.value.details && allForm.value.details.length < 3) {
    allForm.value.details?.unshift({
      order: allForm.value.details.length + 1,
      prefixName: '前缀',
      prefixValue: '',
      del: true,
      placeholder: '自定义输入',
      editKey: true,
      editValue: true,
      auto: 1
    });
    return;
  } else {
    Message.error('前缀不能超过3个');
  }
};

// 时间处理函数
const disposeTime = (status?: number) => {
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  return status
    ? `${year}${month < 10 ? '0' + month : month}`
    : `${year}${month < 10 ? '0' + month : month}${day < 10 ? '0' + day : day}`;
};

// 新增年月日前缀
const timer = (e: 1 | 2) => {
  if (allForm.value.details.length >= 3)
    return Message.error('前缀不能超过3个');
  const arr = [
    {
      order: allForm.value.details.length + 1,
      prefixName: '年月',
      prefixValue: disposeTime(1),
      del: true,
      editKey: false,
      editValue: false,
      placeholder: '自定义输入',
      auto: 2
    },
    {
      order: allForm.value.details.length + 1,
      prefixName: '年月日',
      prefixValue: disposeTime(),
      del: true,
      editKey: false,
      editValue: false,
      placeholder: '自定义输入',
      auto: 3
    }
  ];
  allForm.value.details.push(arr[e - 1]);
  disabled.value = true;
};

// 确认按钮
const handleBeforeOk = async () => {
  if (!props.show) {
    if ((await refForm.value.validate()) || (await refForm2.value.validate())) {
      return;
    }
    if (allForm.value.details.length === 0) {
      Message.error('必须至少有一个前缀！');
      return;
    }

    allForm.value.example = jobNumber.value;
    allForm.value.numId = allForm.value.positionSequenceId;
    allForm.value.prefix = '';
    allForm.value.details.forEach((ele, index) => {
      ele.order = index + 1;
      // if (index !== allForm.value.details.length - 1) {
      //   allForm.value.prefix += ele.prefixValue;
      // } else allForm.value.prefix += '年月';
    });

    if (allForm.value.id) {
      Modal.open({
        title: '修改工号',
        content: <h3>修改工号后工号流水会重新清空并重新生成！</h3>,
        onOk: async () => {
          allForm.value.nowNum = 1; // 每次修改清空nowNum
          await EditScheme(allForm.value);
          emit('update:visible', false);
          await props.refreshFn();
        }
      });
    } else {
      const res = await RepeatScheme({
        prefix: allForm.value.prefix
      });
      if (res.code) {
        Message.error(res.msg);
        return;
      }
      await PostScheme(allForm.value);
      emit('update:visible', false);
      await props.refreshFn();
    }
    disabled.value = false;
  }
};

// 关闭弹窗
const handleCancel = () => {
  init();
  emit('update:visible', false);
};
</script>
<style lang="less" scoped>
:deep(.arco-space-item) {
  justify-content: center;
  margin-right: 0px !important;
}
:deep(.arco-form-item-label-tooltip) {
  color: #ffa0a0;
}
:deep(.arco-input-wrapper) {
  width: 60%;
}
:deep(.arco-form-item-content-wrapper) {
  width: 60%;
}
.job-number {
  margin: 20px 0;
  background-color: #f2f2f2;
  height: 50px;
  color: #3d90fc;
  display: block;
}
</style>
